package com.jgame.secondarymarket.infrastructure.config;

import com.jgame.secondarymarket.infrastructure.common.model.response.Result;
import com.jgame.secondarymarket.infrastructure.excetpions.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLSyntaxErrorException;
import java.util.List;

/**
 * @title: GlobalExceptionHandler
 * @Author Wangsj
 * @Date: 2021/7/22
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result MyExceptionHandle(MethodArgumentNotValidException exception) {
        exception.printStackTrace();
        BindingResult result = exception.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();

        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(error -> {
                log.error("field" + error.getField() + ", msg:" + error.getDefaultMessage());
                errorMsg.append(error.getDefaultMessage()).append("!");
            });
        }
        return Result.error(-2, errorMsg.toString());
    }

    @ExceptionHandler(value = SQLSyntaxErrorException.class)
    @ResponseBody
    public Result SqlExceptionHandle(SQLSyntaxErrorException exception) {
        exception.printStackTrace();
        return Result.error(-5, exception.getMessage().toString());
    }

    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result BaseExceptionHandle(BaseException exception) {
        exception.printStackTrace();
        return Result.error(-1, exception.getMessage().toString());
    }
}
